//
//  PaiDanViewController.m
//  Rabbit
//
//  Created 阿帕 on 2019/12/20.
//  Copyright © 2019 GCY. All rights reserved.
//

#import "PaiDanViewController.h"
#import "NYSExInputAlert.h"
#import "FFPopup.h"
#import "SiJiCell.h"
#import "CYWebViewViewController.h"

@interface PaiDanViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    NSString *_driverCode;
    NSString *_vehicleCode;
}
@property (strong, nonatomic) NYSExInputAlert *inputAlertView;

@property (strong , nonatomic)UITextField *textFiled;

@property (strong , nonatomic)UITableView *tableView;

@property (strong , nonatomic)NSMutableArray *dataArray;

@property (strong , nonatomic)UIImageView *foundImageView;

@property (strong , nonatomic)UIButton *confirmButton;

@property (nonatomic, assign) NSInteger pageNum;

@property (nonatomic, strong) UIButton *xieYiButton;

@property (nonatomic, assign) BOOL isAgreeProtocol;

@end

@implementation PaiDanViewController

static const CGFloat cellHeight = 120;

- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.isAgreeProtocol = NO;
    _pageNum = 1;
    _driverCode = @"";
    _vehicleCode = @"";
    
    [self baseViewSetup];
}

- (void)baseViewSetup {
    
    self.navigationItem.title = @"选择承运司机";
    
    self.view.backgroundColor = BackgroundColor;
    
    _textFiled = [[UITextField alloc] initWithFrame:CGRectMake(0, 10, ScreenW, 40)];
    _textFiled.font = font(14);
    _textFiled.text = @"";
    _textFiled.backgroundColor = [UIColor whiteColor];
    _textFiled.clearButtonMode = UITextFieldViewModeWhileEditing;
    _textFiled.keyboardType = UIKeyboardTypeDefault;
    _textFiled.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"司机名称/手机号/车牌号" attributes:@{NSForegroundColorAttributeName: Light_TextColor}];
    _textFiled.clearButtonMode = UITextFieldViewModeWhileEditing;
    
//    UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 15, 40)];
    _textFiled.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 15, 40)];
    _textFiled.leftViewMode = UITextFieldViewModeAlways;
//    [_textFiled addSubview: leftView];
    
    
    UIImageView *searchImage = [[UIImageView alloc]initWithFrame:CGRectMake(ScreenW-40, 10, 20, 20)];
    searchImage.userInteractionEnabled = YES;
    searchImage.image = [UIImage imageNamed:@"gcy_icon_search_siji"];
    _textFiled.rightView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
    _textFiled.rightViewMode = UITextFieldViewModeAlways;
    
    [searchImage nyl_addTapGes:^{
        _pageNum = 1;
        [self driverListRequest];
    }];
    
    [_textFiled addSubview:searchImage];
    
    [self.view addSubview:_textFiled];
    
    [self.view addSubview:self.tableView];
    
    [self.view addSubview:self.xieYiButton];
    
    [self.view addSubview:self.confirmButton];
    
    [self driverListRequest];
}

- (void)driverListRequest {
    WEAKSELF
    
    if (_pageNum == 1) {
        [self.dataArray removeAllObjects];
    }
    
    NSDictionary *params = @{
        @"isTeamSendDetail": @"1",
        @"searchInfo": _textFiled.text,
        @"pageSize":DEFULT_LOAD_NUM,
        @"pageNum":[NSNumber numberWithInteger:_pageNum],
        @"branchCodeExt": _branchCode,
        @"token":[UserDefaultUtil valueForKey:USER_TOKEN],
    };
    
    [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl], DRIVER_TEAMDRIVERLIST) withParameter:params withVC:self netName:@"车队查询自己旗下司机列表" success:^(id response, NSString *msg) {
        
        if ([response[@"records"] count] != 0) {
            
            [weakSelf.dataArray addObjectsFromArray:[SiJiListModel mj_objectArrayWithKeyValuesArray:response[@"records"]]];
            [weakSelf.tableView.mj_header endRefreshing];
            [weakSelf.tableView.mj_footer endRefreshing];
            
            weakSelf.foundImageView.hidden = YES;
            weakSelf.tableView.hidden = NO;
            
        }else{
            if (_pageNum == 1) {
                weakSelf.foundImageView.hidden = NO;
                weakSelf.tableView.hidden = YES;
            }
            
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
            
        }
        
        [self.tableView reloadData];
        
    } failure:^(NSInteger code, NSString *msg) {
        
    }];
    
}
//上拉刷新数据
- (void)loadNewData{
    _pageNum = 1;
    [self driverListRequest];
}
- (void)loadMoreData{
    _pageNum ++;
    [self driverListRequest];
}

- (void)confirmButtonClick {
    WEAKSELF
    if([DCSpeedy isBlankString:_vehicleCode] == YES){
        [XSInfoView showInfo:@"该司机没有绑定默认车辆无法派单" onView:self.view];
        return;
    }
    if ([DCSpeedy isBlankString:_driverCode] == YES) {
        [XSInfoView showInfo:@"请选择一个承运司机" onView:self.view];
        return;
    }
    if(self.isAgreeProtocol == NO){
        [XSInfoView showInfo:@"请阅读并遵循协议" onView:self.view];
        return;
    }
    
    if (_driverIsShare.boolValue) {
        // 设置信息费
        FFPopup *popup = [FFPopup popupWithContentView:self.inputAlertView showType:FFPopupShowType_BounceIn dismissType:FFPopupDismissType_ShrinkOut maskType:FFPopupMaskType_Dimmed dismissOnBackgroundTouch:NO dismissOnContentTouch:NO];
        FFPopupLayout layout = FFPopupLayoutMake(FFPopupHorizontalLayout_Center, FFPopupVerticalLayout_Center);
        [popup showWithLayout:layout];
        self.inputAlertView.updateTF.text = self.infoFee;
        self.inputAlertView.block = ^(id text) {
            [weakSelf.view endEditing:YES];
            [popup dismissAnimated:YES];
            
            if ([text isEqualToString:@"-1"]) { // 取消
                return;
            }
            
            [weakSelf orderHandle:text];
        };
    } else {
        [self orderHandle:nil];
    }
}

- (void)orderHandle:(NSString *)infoFee {
    WEAKSELF
    NSMutableDictionary *params = @{
        @"code": _orderCode,
        @"driverCode": _driverCode,
        @"vehicleCode": _vehicleCode,
        @"token":[UserDefaultUtil valueForKey:USER_TOKEN]
    }.mutableCopy;
    
    if ([infoFee isNotBlank])
        [params setValue:infoFee forKey:@"infoFee"];
    
    if (_status == 0) {
        
        switch (self.paiDanType) {
            case PaiDanType_ZhiDingYunDan:
                [self paiDanZhiDingYunDanWithParam:params];
                break;
            case PaiDanType_ZhiDingMouCiJieDan:
                [self paiDanMouCiJieDan];
                break;
                
            default:
                break;
        }
        
    } else {
        //调单
        [HTTPManager putNetworkRequest:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-tms-api",[ReAddressDynamic shared].baseUrl], ORDER_DETAIL_DISPATCHORDERDETAIL) withParameter:params withVC:self netName:@"调单" success:^(id response, NSString *msg) {
            
            [XSInfoView showInfo:msg onView:weakSelf.view];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
                [weakSelf.navigationController popViewControllerAnimated:YES];
            });
        } failure:^(NSInteger code, NSString *msg) {
            
        }];
    }
}

/// 针对指定运单派单，将这个运单派给这个司机
- (void)paiDanZhiDingYunDanWithParam:(NSDictionary *)dic {
    //派单
    WEAKSELF
    [HTTPManager postNetworkRequest:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-tms-api",[ReAddressDynamic shared].baseUrl], ORDER_DETAIL_SELECTDRIVERRECEIVE) withParameter:dic withVC:self netName:@"车队派单给司机" success:^(id response, NSString *msg) {
        
        [XSInfoView showInfo:msg onView:weakSelf.view];
                    
        [KNotificationCenter postNotificationName:YUNDANCENTERLIST_REFRESH object:nil];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
            [weakSelf.navigationController popViewControllerAnimated:YES];
        });
        
    } failure:^(NSInteger code, NSString *msg) {
        
    }];
}
/**
 针对某次接单来派单。
 车队长接单后，这一次接单可能包括多个运单，针对这次接单，自动选择运单号最小的一个运单指派给这个司机
 */
- (void)paiDanMouCiJieDan {
    //派单
    WEAKSELF
    NSDictionary *dic = @{
        @"teamOrderCode": StringCheck(self.code),
        @"driverCode": StringCheck(_driverCode),
        @"vehicleCode" : StringCheck(_vehicleCode),
    };
    NSString *url = CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-tms-api",[ReAddressDynamic shared].baseUrl], @"/teamOrder/dispatch");
    [HTTPManager jsonNetworkRequestWithMethod:@"POST" urlString:url withParameter:dic withVC:nil netName:@"车队角色，针对某次接单，派单给司机" success:^(id response, NSString *msg) {
        [XSInfoView showInfo:msg onView:weakSelf.view];
        [KNotificationCenter postNotificationName:YUNDANCENTERLIST_REFRESH object:nil];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
            [weakSelf.navigationController popViewControllerAnimated:YES];
        });

    } failure:^(NSInteger code, NSString *msg) {
        
    }];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    SiJiCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SiJiCellID"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    cell.model = self.dataArray[indexPath.row];
    
    return cell;
}

#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return cellHeight;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.001f;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    //    CYCreditCardDetailViewController *ccdvc = [[CYCreditCardDetailViewController alloc] init];
    //    CreditCardListModel *model = self.dataArray[indexPath.row];
    //    ccdvc.creditCardId = model.cardId;
    //    [self.navigationController pushViewController:ccdvc animated:YES];
    
    //    NSIndexPath *index=[NSIndexPath indexPathForRow:indexPath.row inSection:0];
    
    for (SiJiListModel *model in self.dataArray) {
        model.isSelected = NO;
    }
    SiJiListModel *model = self.dataArray[indexPath.row];
    
    _driverCode = model.partyCode;
    _vehicleCode = model.vehicleCode;
    
    model.isSelected = !model.isSelected;
    [self.tableView reloadData];
    
}

#pragma mark - LazyLoad
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.frame = CGRectMake(0, 51, ScreenW, ScreenH - NavHeight - 51 - 75 - 30);
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        //注册单元格
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([SiJiCell class]) bundle:nil] forCellReuseIdentifier:@"SiJiCellID"];
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    }
    
    return _tableView;
}

- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}
- (UIImageView *)foundImageView {
    if (!_foundImageView) {
        _foundImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 170, 170)];
        _foundImageView.image = image(@"gcy_img_list_found");
        _foundImageView.contentMode = UIViewContentModeScaleAspectFit;
        _foundImageView.cy_centerX = self.view.cy_centerX;
        _foundImageView.cy_centerY = self.view.cy_centerY;
        [self.view addSubview:_foundImageView];
    }
    return _foundImageView;
}
- (UIButton *)xieYiButton{
    if(!_xieYiButton){
        self.xieYiButton = [UIButton buttonWithType:UIButtonTypeCustom];
        self.xieYiButton.tag = 1100;
        self.xieYiButton.titleLabel.font = font(14);
        [self.xieYiButton setTitleColor:Theme_ColorValue forState:UIControlStateNormal];
        [self.xieYiButton setTitle:CJStringWithFormat(@"同意《委托收款授权书》") forState:UIControlStateNormal];
        self.xieYiButton.frame = CGRectMake(50, ScreenH - NavHeight - 65 - 37, ScreenW-40, 30);
        self.xieYiButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [self.xieYiButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:self.xieYiButton.titleLabel.text];
        [attString addAttribute:(NSString*)NSForegroundColorAttributeName value:Light_TextColor range:[self.xieYiButton.titleLabel.text rangeOfString:@"同意"]];
        [attString addAttribute:(NSString*)NSForegroundColorAttributeName value:Theme_ColorValue range:[self.xieYiButton.titleLabel.text rangeOfString:CJStringWithFormat(@"《委托收款授权书》")]];
        [self.xieYiButton setAttributedTitle:attString forState:UIControlStateNormal];
        UIButton *agreeButton = [UIButton buttonWithType:UIButtonTypeCustom];
        agreeButton.tag = 1101;
        [agreeButton setImage:image(@"gcy_img_home_business_nomal") forState:UIControlStateNormal];
        agreeButton.frame = CGRectMake( 15, self.xieYiButton.top, 30, 30);
        [agreeButton addTarget:self action:@selector(xieYiButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:agreeButton];
    }
    return _xieYiButton;
}
- (void)buttonAction:(UIButton *)btn{
    CYWebViewViewController *webVC = [[CYWebViewViewController alloc] init];
    webVC.titleString = @"委托收款授权书";
    webVC.urlString = CJStringWithFormat(@"%@/agreement.html",BasicDomainURL);
    webVC.state = 1;
    [self.navigationController pushViewController:webVC animated:YES];
}

- (void)xieYiButtonAction:(UIButton *)btn{
    btn.selected = !btn.selected;
    if(btn.isSelected){
        self.isAgreeProtocol = YES;
        [btn setImage:image(@"gcy_img_home_business_select") forState:(UIControlStateNormal)];
    }else{
        self.isAgreeProtocol = NO;
        [btn setImage:image(@"gcy_img_home_business_nomal") forState:UIControlStateNormal];
    }
}
- (UIButton *)confirmButton {
    if (!_confirmButton) {
        _confirmButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_confirmButton setTitle:@"确认" forState:UIControlStateNormal];
        [_confirmButton setBackgroundColor:Theme_ColorValue];
        cut(_confirmButton, BTN_BORDER_RADIUS);
        [_confirmButton addTarget:self action:@selector(confirmButtonClick) forControlEvents:UIControlEventTouchUpInside];
        [_confirmButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _confirmButton.frame = CGRectMake(20, ScreenH - NavHeight - 65, ScreenW-40, 45);
    }
    return _confirmButton;
}

- (NYSExInputAlert *)inputAlertView {
    if (!_inputAlertView) {
        CGFloat width = kP6(300.0);
        CGFloat height = kP6(150.0);
        _inputAlertView = [[NYSExInputAlert alloc] initWithFrame:CGRectMake(0, 0, width, height)];
    }
    return _inputAlertView;
}

@end
